package com.dubbo.demo.filter;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;

/**
 * @author liufl
 * @version 创建时间：2017年7月25日 下午5:18:31
 * 类说明
 */
public class LoginInterceptor implements Filter {
	
	Logger log = LoggerFactory.getLogger(this.getClass());
    
	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation)
			throws RpcException {
		long start = System.currentTimeMillis();  
        Result result = invoker.invoke(invocation);  
        long elapsed = System.currentTimeMillis() - start;  
        if (invoker.getUrl() != null) {
        	String rpc = "[{" +invoker.getInterface()+"}]"+",[{"+ invocation.getMethodName()+"}]"+",[{"+   
                    Arrays.toString(invocation.getArguments())+"}]"+",[{"+  result.getValue()+"}]"+",[{"+   
                  result.getException()+"}]"+",[{"+  elapsed+"}]";
            log.info("rpc:"+rpc);  
            System.out.println("rpc:"+rpc);
        }  
        boolean isConsumerSide = RpcContext.getContext().isConsumerSide(); //
        //本端是否为消费端
        String serverIP = RpcContext.getContext().getRemoteHost()+":"+RpcContext.getContext().getRemotePort(); //
        //获取当前线程最后一次调用的提供方IP地址
        String application = RpcContext.getContext().getUrl().getParameter("application");//
        //获取当前服务配置信息(笔者注:为consumer,无法获取provider的application地址)，所有配置信息都将转换为URL的参数
        String localAddr = RpcContext.getContext().getLocalAddressString();
        String other = "[isConsumerSide:"+isConsumerSide+"],[serverIP:"+serverIP+"],[application:"+application+"],[localAddr:"+localAddr+"]";
        log.info(other);  
        System.out.println(other);
		return result;
	}
}

